// pages/activity/inviteFriends/index.js
const api = require('../../../config/api')
const request = require('../../../utils/request')
const app = getApp()
const { saveImage } = require('../../../utils/photo')
const env = __wxConfig.envVersion
Page({
  /**
   * 页面的初始数据
   */
  data: {
    activityActive: true, // 活动是否正在进行
    isNewUser: true, // 是否为新用户
    sceneList: [], // 问卷列表
    showSceneList: [],
    showAll: false,
    showPoster: false,
    posterImg:
      'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backendf68dc8b96f094aef99a66aedfda1c103.png',
    codeImg: '', // 用户小程序码
    imagePath: '',
    canvasHeight: 0,
    canvasWidth: 0,
    activityId: '',
    activityType: 2,
    isPutaway: 1, // 是否上架，0/下架，1/上架
    env: env,
    canvasLeft: 48,
    activityDialogShow: false,
    hadLogin: app.isLogin(),
    inviteList: [],
    emptyObj: {
      appletUserId: '',
      createTime: '',
      headUrl: '',
      nickname: '',
    },
    shareActivityId: '',
    awardImgs1:
      'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend4c27cccdc5a644968e834563f6bf4787.png',
    awardImgs2:
      'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend8cab0e20f2804d81906defaf4c73526b.png',
    awardImgs3:
      'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend2297c2f07b204aa394cf860521df4db3.png',
    bgHeight: 2066,
    modalHeight: app.kBottomSafeHeight+ 345
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options?.activityId) {
      this.setData({
        activityId: options?.activityId,
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let { emptyObj } = this.data
    this.setData({
      hadLogin: app.isLogin(),
    })
    this.getActivityDetail()
    if (app.isLogin()) {
      this.getQRCode()
      this.getInviteList()
    } else {
      let arr1 = new Array(3).fill(emptyObj)
      let arr2 = new Array(3).fill(emptyObj)
      let arr3 = new Array(4).fill(emptyObj)
      this.setData({
        threeInviteList: arr1,
        sixInviteList: arr2,
        tenInviteList: arr3,
      })
    }
  },
  // 获取活动详情
  async getActivityDetail() {
    let { activityId } = this.data
    const res = await request.get(
      api.activityDetail,
      {
        activityId: activityId,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      let info = res.data
      this.setData({
        activityActive: !app.isLogin()
          ? true
          : info.activityState === 2 && info.isPutaway === 1,
        activityType: info.activityType,
        isPutaway: info.isPutaway,
        shareActivityId: info.shareActivityId,
      })
      wx.setNavigationBarTitle({
        title: info.activityTitle || '邀好友，免费领',
      })
    }
  },
  // 生成小程序码
  async getQRCode() {
    let { activityId } = this.data
    const res = await request.get(
      api.createQrcodeImg,
      {
        activityId: activityId,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      this.setData({
        codeImg: res.data,
      })
      this.savePhoto()
    }
  },
  // 邀请记录列表
  async getInviteList() {
    let { activityId } = this.data
    const res = await request.get(
      api.inviteList,
      {
        activityId: activityId,
      },
      { loading: false }
    )
    if (res.httpStatus === 200) {
      let length = res.data?.length
      this.setData({
        inviteList: res.data,
        bgHeight: length > 6 ? (length - 6) * 100 + 2066 : 2066,
      })
      this.handleInviteList()
    }
  },
  // 邀请列表处理
  handleInviteList() {
    let { inviteList, emptyObj } = this.data
    let arr1 = new Array(3).fill(emptyObj)
    let arr2 = new Array(3).fill(emptyObj)
    let arr3 = new Array(4).fill(emptyObj)

    inviteList.map((item, index) => {
      if (index < 3) {
        arr1[index] = item
      }
      if (index >= 3 && index < 6) {
        arr2[index - 3] = item
      }
      if (index >= 6 && index < 10) {
        arr3[index - 6] = item
      }
    })

    this.setData({
      threeInviteList: arr1,
      sixInviteList: arr2,
      tenInviteList: arr3,
    })
  },
  // 跳转活动规则
  handleRule() {
    let { activityType } = this.data
    wx.navigateTo({
      url:
        '/pages/activity/inviteFriendsRule/index?activityType=' + activityType,
    })
  },
  // 点击查看更多
  handleMore() {
    let { showAll, sceneList } = this.data
    let arr = sceneList.slice(0, 5)
    this.setData({
      showSceneList: showAll ? arr : sceneList,
      showAll: !showAll,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.shareSheet = this.selectComponent('#shareSheet')
  },
  // 显示分享弹窗
  showShareSheet() {
    let { activityId } = this.data
    const router = `/pages/activity/inviteFriends/index?activityId=${activityId}`
    if (!app.isLogin()) {
      wx.setStorageSync('activityId', activityId)
      app.navTo(router)
    } else {
      this.setData({
        showPoster: true,
      })
      this.shareSheet.show()
    }
  },
  // 隐藏分享弹窗
  hideShareSheet() {
    this.setData({
      showPoster: false,
    })
    this.shareSheet.hide()
  },
  // 将海报地图与用户小程序码合并成一张图
  savePhoto: function () {
    let that = this
    let { posterImg, codeImg } = that.data
    wx.downloadFile({
      url: posterImg,
      success(res) {
        const ctx = wx.createCanvasContext('myCanvas', that)
        wx.getImageInfo({
          src: posterImg,
          success: function (res) {
            // 绘制背景海报到canvas

            var sysInfo = wx.getSystemInfoSync()
            let windowWidth = sysInfo.windowWidth
            var scale = (windowWidth / 375) * 0.92 //不同屏幕下canvas的适配比例；设计稿是750宽

            let imgW = 280 * scale // 274
            let imgH = 407 * scale // 407
            let imgPath = res.path

            let codeSize = 75 * scale

            that.setData({
              canvasHeight: imgH,
              canvasWidth: imgW,
              canvasLeft: (windowWidth - imgW) / 2,
            })
            ctx.drawImage(imgPath, 0, 0, imgW, imgH)
            wx.getImageInfo({
              src: codeImg,
              success: function (res) {
                // 图片的x坐标
                let bg_x = (imgW - codeSize) / 2 // 10
                // 图片的y坐标
                let bg_y = imgH - codeSize - 8 // 70
                // 图片宽度
                let bg_w = codeSize
                // 图片高度
                let bg_h = codeSize
                // 图片圆角
                let bg_r = 6

                // 绘制小程序码圆角
                ctx.save()
                ctx.beginPath()
                ctx.arc(bg_x + bg_r, bg_y + bg_r, bg_r, Math.PI, Math.PI * 1.5)
                ctx.arc(
                  bg_x + bg_w - bg_r,
                  bg_y + bg_r,
                  bg_r,
                  Math.PI * 1.5,
                  Math.PI * 2
                )
                ctx.arc(
                  bg_x + bg_w - bg_r,
                  bg_y + bg_h - bg_r,
                  bg_r,
                  0,
                  Math.PI * 0.5
                )
                ctx.arc(
                  bg_x + bg_r,
                  bg_y + bg_h - bg_r,
                  bg_r,
                  Math.PI * 0.5,
                  Math.PI
                )
                ctx.clip()
                ctx.drawImage(res.path, bg_x, bg_y, bg_w, bg_h)
                // 恢复之前保存的绘图上下文
                // ctx.restore()
                ctx.draw()

                setTimeout(() => {
                  wx.canvasToTempFilePath(
                    {
                      canvasId: 'myCanvas',
                      success: function (res) {
                        that.setData({
                          imagePath: res.tempFilePath,
                        })
                      },
                      fail: function (res) {},
                    },
                    this
                  )
                }, 1000)
              },
            })
          },
        })
      },
    })
  },
  // 保存海报
  handleSave() {
    wx.showLoading({
      title: '保存中...',
      mask: true
    })
    setTimeout(()=>{
      wx.hideLoading()
      let { imagePath } = this.data
      saveImage(imagePath)
    },1500)
  },
  // 关闭活动弹窗
  handleCloseActivity() {
    this.setData({
      activityDialogShow: false,
    })
  },
  // 点击领取奖励
  handleReward() {
    this.setData({
      activityDialogShow: true,
    })
  },
  // 点击查看图片大图
  handlePreview(val) {
    let { awardImgs1, awardImgs2, awardImgs3 } = this.data
    let arr = [awardImgs1, awardImgs2, awardImgs3]
    let url = val.currentTarget.dataset.url
    wx.previewImage({
      current: url, //当前图片地址
      urls: arr, //所有要预览的图片的地址集合 数组形式
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { shareActivityId } = this.data
    const userId = wx.getStorageSync('userId')
    return {
      title: '邀你和我一起培养天才宝宝',
      path: `/pages/index/index?activityId=${shareActivityId}&userId=${userId}`,
      imageUrl:
        'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend214be006804e4ce4a905e603361a7613.png',
    }
  },
})
